<?php

namespace AdminBundle\Controller;

use AdminBundle\Entity\AuthLinkUserGroups;
use AdminBundle\Entity\AuthUser;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Request;
use AdminBundle\Utility\Constant;

/**
 * Authuser controller.
 *
 * @Route("authuser")
 */
class AuthUserController extends BaseController
{

    /**
     * Lists all authUser entities.
     *
     * @Route("/", name="authuser_index")
     * @Method("GET")
     */
    public function indexAction(Request $request)
    {
        $page = $request->get("page");
        $page = is_numeric($page) ? $page : 1;
        $keyword = $request->get('keyword');
        $date_range = $request->get('date_range');
        $starttime = $request->get('starttime');
        $endtime = $request->get('endtime');

        $starttime = $starttime ? $starttime : date("Y-m-d", strtotime("-1 day"));
        $endtime = $endtime ? $endtime : date("Y-m-d", strtotime("+1 day"));

        $params = ['keyword' => $keyword, 'starttime' => $starttime, 'endtime' => $endtime];

        $result = $this->getDoctrine()->getRepository('AdminBundle:AuthUser')->pageQuery($params, $page);

        return $this->render('AdminBundle:authuser:index.html.twig', array_merge([
            'authUsers' => $result['list'],
            'querystring' => http_build_query($params),
            'page' => $result['page'],
        ], $params));
    }

    /**
     * Creates a new authUser entity.
     *
     * @Route("/new", name="authuser_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        $authUser = new Authuser();
        $form = $this->createForm('AdminBundle\Form\AuthUserType', $authUser, Constant::FORM_ATTR_CLASS);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $authUser->setCtime(new \DateTime());
            $authUser->setCreateUser($this->getUser()->getUsername());
            $em = $this->getDoctrine()->getManager();
            $em->persist($authUser);
            $em->flush();

            $this->assignGroup($request, $authUser);

            return $this->redirectToRoute('authuser_show', array('id' => $authUser->getId()));
        }

        $authGroups = $this->getDoctrine()->getRepository('AdminBundle:AuthUser')->loadGroup();

        return $this->render('AdminBundle:authuser:new.html.twig', array(
            'authUser' => $authUser,
            'form' => $form->createView(),
            'authGroups' => $authGroups
        ));
    }

    public function assignGroup(Request $request, Authuser $authuser)
    {
        $groups = [];
        // 设置用户的组
        $auth_user = $request->request->get('auth_user', []);
        if (isset($auth_user['group']) && !empty($auth_user['group'])) {
            $em = $this->getDoctrine()->getManager();

            $groups = $auth_user['group'];
            foreach ($groups as $group) {
                // 滤重
                $obj_is_exists = $em->getRepository('AdminBundle:AuthUser')->loadByUserIdAndGroupId(
                    $authuser->getId(), trim($group)
                );
                if ($obj_is_exists != null)
                    continue;
                // 权限
                $authGroup = $em->getRepository('AdminBundle:AuthGroup')->findOneBy(['id' => $group]);

                $authLinkUserGroups = new AuthLinkUserGroups();
                $authLinkUserGroups->setCreateUser($this->getUser()->getUsername())
                    ->setCtime(new \DateTime())
                    ->setUser($authuser)
                    ->setGroup($authGroup);
                $em->persist($authLinkUserGroups);
            }
            $em->flush();
        }
        return $groups;
    }

    /**
     * Finds and displays a authUser entity.
     *
     * @Route("/{id}", name="authuser_show")
     * @Method("GET")
     */
    public function showAction(AuthUser $authUser)
    {
        $deleteForm = $this->createDeleteForm($authUser);

        return $this->render('AdminBundle:authuser:show.html.twig', array(
            'authUser' => $authUser,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing authUser entity.
     *
     * @Route("/{id}/edit", name="authuser_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, AuthUser $authUser)
    {
        $deleteForm = $this->createDeleteForm($authUser);
        $editForm = $this->createForm('AdminBundle\Form\AuthUserType', $authUser, Constant::FORM_ATTR_CLASS);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            $groupIds = $this->assignGroup($request, $authUser);

            $ret = $this->getDoctrine()->getRepository('AdminBundle:AuthUser')->revokeUserGroup($authUser->getId(), $groupIds);

            return $this->redirectToRoute('authuser_edit', array('id' => $authUser->getId()));
        }
        $authGroups = $this->getDoctrine()->getRepository('AdminBundle:AuthUser')->loadGroup($authUser->getId());

        return $this->render('AdminBundle:authuser:edit.html.twig', array(
            'dataSource' => $authUser,
            'form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
            'authGroups' => $authGroups
        ));
    }

    /**
     * Deletes a authUser entity.
     *
     * @Route("/{id}", name="authuser_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, AuthUser $authUser)
    {
        $form = $this->createDeleteForm($authUser);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            // 清除已分配的权限
            $ret = $em->getRepository('AdminBundle:AuthUser')->revokeUserGroup($authUser->getId());

            $em->remove($authUser);
            $em->flush();
        }

        return $this->redirectToRoute('authuser_index');
    }

    /**
     * Creates a form to delete a authUser entity.
     *
     * @param AuthUser $authUser The authUser entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(AuthUser $authUser)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('authuser_delete', array('id' => $authUser->getId())))
            ->setMethod('DELETE')
            ->getForm();
    }
}
